package com.zhentao.filter;

import com.zhentao.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.core.*;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的url，登录的路径放行
        String path = request.getURI().getPath();
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        //不是登录路径的话，判断是否有登录
        //获取token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            //token为空，重新登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //获取token之后判断是否有效
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int tokenValue = AppJwtUtil.verifyToken(claimsBody);
            if (tokenValue == 1 || tokenValue == 2) {//token过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //token是正确的  咱们在执行操作的时候需要用到userId, -token
            Object userId = claimsBody.get("id");
            //其他的业务里面要用到这个用户id  现在在过滤器里面
            // 把userId放到header里面
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId + "");
            }).build();

            //重置header
            exchange.mutate().request(serverHttpRequest);
        } catch (Exception e) {
            //解密失败，重新登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //token有效进行放行

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
